package com.lst.projectlib.component.datetimepicker;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import com.lst.projectlib.R;
import com.lst.projectlib.util.DensityUtil;

public class DoubleDatePickerActivity extends Activity implements
		OnClickListener, OnDateChangedListener {

	public static final String INTENT_BUNDLE_KEY_INITIAL_YEAR_LEFT = "initial_year_left";
	public static final String INTENT_BUNDLE_KEY_INITIAL_MONTH_LEFT = "initial_month_left";
	public static final String INTENT_BUNDLE_KEY_INITIAL_DAY_LEFT = "initial_day_left";
	public static final String INTENT_BUNDLE_KEY_INITIAL_YEAR_RIGHT = "initial_year_right";
	public static final String INTENT_BUNDLE_KEY_INITIAL_MONTH_RIGHT = "initial_month_right";
	public static final String INTENT_BUNDLE_KEY_INITIAL_DAY_RIGHT = "initial_day_right";
	public static final String INTENT_BUNDLE_KEY_INITIAL_TITLE = "initial_title";
	public static final String INTENT_BUNDLE_KEY_SELECT_DOUBLE_DATE = "select_double_date";

	private DatePicker mDatePickerLeft;
	private DatePicker mDatePickerRight;

	private int request_code = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.activity_double_date_picker);

		TextView tv_ok = (TextView) this.findViewById(R.id.tv_ok);
		TextView tv_cancel = (TextView) this.findViewById(R.id.tv_cancel);
		tv_ok.setOnClickListener(this);
		tv_cancel.setOnClickListener(this);

		mDatePickerLeft = (DatePicker) this.findViewById(R.id.date_picker_left);
		mDatePickerRight = (DatePicker) this.findViewById(R.id.date_picker_right);
		
		resizePikcer(mDatePickerLeft);
		resizePikcer(mDatePickerRight);
		
		initData();
	}

	private void initData() {
		Intent intent = getIntent();

		if (intent != null) {
			int leftYear = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_YEAR_LEFT, 0);
			int leftMonth = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_MONTH_LEFT, 0);
			int leftDay = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_DAY_LEFT, 0);
			int rightYear = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_YEAR_RIGHT, 0);
			int rightMonth = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_MONTH_RIGHT, 0);
			int rightDay = intent.getIntExtra(INTENT_BUNDLE_KEY_INITIAL_DAY_RIGHT, 0);

			// 系统拿到的月份会小1（应该是从0计算的，所以得自己做处理，减去1）
			leftMonth--;
			rightMonth--;

			mDatePickerLeft.init(leftYear, leftMonth, leftDay, this);
			mDatePickerRight.init(rightYear, rightMonth, rightDay, this);

			request_code = intent.getIntExtra("request_code", 0);
			// txt_title.setText(intent
			// .getStringExtra(INTENT_BUNDLE_KEY_INITIAL_TITLE));
		}
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.tv_cancel) {
			finish();
		} else if (v.getId() == R.id.tv_ok) {
			int leftYear = mDatePickerLeft.getYear();
			int leftMonth = mDatePickerLeft.getMonth();
			int leftDay = mDatePickerLeft.getDayOfMonth();
			int rightYear = mDatePickerRight.getYear();
			int rightMonth = mDatePickerRight.getMonth();
			int rightDay = mDatePickerRight.getDayOfMonth();
			
			if (leftYear > rightYear) {
				Toast.makeText(this, "起始时间不能大于终止时间", Toast.LENGTH_SHORT).show();
				return;
			}
			if (leftYear == rightYear) {
				if (leftMonth > rightMonth) {
					Toast.makeText(this, "起始时间不能大于终止时间", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				if (leftMonth == rightMonth) {
					if (leftDay > rightDay) {
						Toast.makeText(this, "起始时间不能大于终止时间", Toast.LENGTH_SHORT)
								.show();
						return;
					}
				}
			}

			tryNotifyTimeSet();
			finish();
		}
	}

	private void tryNotifyTimeSet() {
		if (mDatePickerLeft != null && mDatePickerRight != null) {
			mDatePickerLeft.clearFocus();
			mDatePickerRight.clearFocus();

			Intent intent = new Intent();
			intent.putExtra("request_code", request_code);

			// 起始时间
			String leftYear = String.valueOf(mDatePickerLeft.getYear());

			// 系统拿到的月份会小1（应该是从0计算的，所以得自己做处理，加上1）
			int nLeftMonth = mDatePickerLeft.getMonth() + 1;
			String leftMonth = nLeftMonth < 10 ? ("0" + nLeftMonth) : String
					.valueOf(nLeftMonth);

			int nLeftDay = mDatePickerLeft.getDayOfMonth();
			String leftDay = nLeftDay < 10 ? ("0" + nLeftDay) : String.valueOf(nLeftDay);
			
			// 终止时间
			String rightYear = String.valueOf(mDatePickerRight.getYear());

			// 系统拿到的月份会小1（应该是从0计算的，所以得自己做处理，加上1）
			int nRightMonth = mDatePickerRight.getMonth() + 1;
			String rightMonth = nRightMonth < 10 ? ("0" + nRightMonth) : String
					.valueOf(nRightMonth);

			int nRightDay = mDatePickerRight.getDayOfMonth();
			String rightDay = nRightDay < 10 ? ("0" + nRightDay) : String.valueOf(nRightDay);

			intent.putExtra(INTENT_BUNDLE_KEY_SELECT_DOUBLE_DATE, leftYear + "/"
					+ leftMonth + "/" + leftDay + "-" + rightYear + "/" + rightMonth + "/" + rightDay);
			this.setResult(RESULT_OK, intent);
		}
	}

	@Override
	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {

	}
	
	/**
	 * 调整FrameLayout大小
	 * @param tp
	 */
	private void resizePikcer(FrameLayout tp) {
		try {
			List<NumberPicker> npList = findNumberPicker(tp);
			for (NumberPicker np : npList) {
				resizeNumberPicker(np);
			}
		} catch (Exception e) {
		}
	}
	
	/**
	 * 得到viewGroup里面的numberpicker组件
	 * @param viewGroup
	 * @return
	 */
	private List<NumberPicker> findNumberPicker(ViewGroup viewGroup){
		List<NumberPicker> npList = new ArrayList<NumberPicker>();
		View child = null;
		if(null != viewGroup){
			for(int i = 0; i < viewGroup.getChildCount(); i++){
				child = viewGroup.getChildAt(i);
				if(child instanceof NumberPicker){
					npList.add((NumberPicker)child);
				}
				else if(child instanceof LinearLayout){
					List<NumberPicker> result = findNumberPicker((ViewGroup)child);
					if(result.size()>0){
						return result;
					}
				}
			}
		}
		return npList;
	}
	
	/*
	 * 调整numberpicker大小
	 */
	private void resizeNumberPicker(NumberPicker np){
		if (np != null) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px(this, 50), LinearLayout.LayoutParams.WRAP_CONTENT);
			params.setMargins(DensityUtil.dip2px(this, 5), 0, DensityUtil.dip2px(this, 5), 0);
			np.setLayoutParams(params);
		}
	}
}
